use crate::ffi_c::{EngineIntLsr, EngineStringLsr};
use std::ffi::{c_void, CString};

pub(crate) struct ContextPtr(pub *const c_void);

unsafe impl Send for ContextPtr {}

unsafe impl Sync for ContextPtr {}

impl ContextPtr {
    pub(crate) fn string_listener(&self, listener_opt: EngineStringLsr, string: String) {
        if let Some(listener) = listener_opt {
            listener(self.0, string.as_str().to_cstring().as_ptr());
        }
    }

    pub(crate) fn int_listener(&self, listener_opt: EngineIntLsr, int: i64) {
        if let Some(listener) = listener_opt {
            listener(self.0, int);
        }
    }
}

pub(crate) trait ToCString {
    fn to_cstring(&self) -> CString;
}

impl ToCString for &str {
    /// 根据 &str 创建新的 CString 对象，返回 *const c_char 指针和所有权
    fn to_cstring(&self) -> CString {
        CString::new(*self).unwrap_or_else(|e| CString::new("").unwrap())
    }
}

impl ToCString for String {
    /// 根据 String 创建新的 CString 对象，返回 *const c_char 指针和所有权
    fn to_cstring(&self) -> CString {
        self.as_str().to_cstring()
    }
}
